iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 3
0
Modern Web

師父領進門 修行在個人系列 第 6

JS挑戰-(3)- Flexbox + Ajax

  • 分享至 

  • xImage
  •  

繼續加油。


  1. 05-Flex Panels Image Gallery
    • 重點
      • css: Flex複習(很棒的複習,喜歡他的整體風格,Flex好重要)
        • nested的 flex感覺可以再更了解一點
        • ps 他還有另外一個Flexbox的課程,推薦給大家
      • js: 複習之前學到的addEventListener of click, transitionend 搭配出效果
    const panels = document.querySelectorAll('.panel');

    function toggleOpen() {
      this.classList.toggle('open');
    }
    function toggleOpenActive(e) {
      console.log(e.propertyName);
      if(e.propertyName.includes('flex')){
        this.classList.toggle('open-active');
      }
    }
    panels.forEach(panel => panel.addEventListener('click',toggleOpen));
    panels.forEach(panel => panel.addEventListener('transitionend',toggleOpenActive));

2.06-Ajax Type Ahead

  • 這張是目前覺得自己最不會的地方,Ajax什麼同步非同步真的都是自學者的痛啊,像是一個新的領域一樣

  • 土法煉鋼,想辦法跟著打,邊打邊學,多打幾次希望會渡過障礙。

  • 這幾天都每天redo一次吧

  • 重點:fetch(), regex, .innerHTML

  • 補充: Regex,RegExp 正規表示式

//資料來源
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';

const cities = [];
//fetch()學習
fetch(endpoint)
    .then(blob => blob.json())
    .then(data => cities.push(...data))


function findMatches(wordToMatch, cities){
  return cities.filter(place => {
    const regex = new RegExp(wordToMatch, 'gi');
    return place.city.match(regex) || place.state.match(regex);
  });
}
//number format
function numberWithCommas(x){
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}


function displayMatches(){
  //get data first, and then others
  const matchArray = findMatches(this.value, cities);
  //json to html
  const html = matchArray.map(place => {
    //style
    const regex = new RegExp(this.value, 'gi');
    const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
    const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);

    //return
    return`
      <li>
        <span class="name">${cityName}, ${stateName}</span>
        <span class="population">${numberWithCommas(place.population)}</span>
      </li>
    `;
  }).join('');
  suggestions.innerHTML = html ;
}


const searchInput = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');

searchInput.addEventListener('change', displayMatches);
searchInput.addEventListener('keyup', displayMatches);


上一篇
JS挑戰-(2)- CSS variable + Array
下一篇
JS挑戰-(4)- Array + HTML5 Canvas
系列文
師父領進門 修行在個人30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言